package com.breadenglish.cms.api.app.sys.service.impl;

import com.breadenglish.cms.api.app.common.utils.PropertyConfigurerUtils;
import com.breadenglish.cms.api.app.dao.FileDao;
import com.breadenglish.cms.api.app.dao.UseFileDao;
import com.breadenglish.cms.api.app.dao.WordDao;
import com.breadenglish.cms.api.app.domain.constants.Constants;
import com.breadenglish.cms.api.app.domain.db.File;
import com.breadenglish.cms.api.app.domain.db.UseFile;
import com.breadenglish.cms.api.app.domain.db.Word;
import com.breadenglish.cms.api.app.domain.exception.BusinessException;
import com.breadenglish.cms.api.app.domain.query.WordQuery;
import com.breadenglish.cms.api.app.sys.service.WordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Created by lixuegang on 2016/1/5.
 */
@Service("wordService")
public class WordServiceImpl implements WordService {

    private static final Logger logger = LoggerFactory.getLogger(WordServiceImpl.class);

    @Resource
    private WordDao wordDao;

    @Resource
    private FileDao fileDao;

    @Resource
    private UseFileDao useFileDao;

    /**
     * 根据主键查询Word对象
     *
     * @param wordId
     * @return Word对象
     */
    @Override
    public Word selectByPrimaryKey(Long wordId) {
        return wordDao.selectByPrimaryKey(wordId);
    }

    /**
     * 根据查询条件查询符合条件的Word对象
     *
     * @param word
     * @return 符合条件的Word对象List
     */
    @Override
    public List<Word> select(Word word) {
        return wordDao.select(word);
    }

    /**
     * 根据主键删除Word对象
     *
     * @param wordId
     * @return 影响条件数
     */
    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public int deleteByPrimaryKey(String wordId) throws Throwable {
        int result = 0;
        String[] ids = wordId.split(":");
//        Word word = new Word();
        for (int i = 0; i < ids.length; i++) {
//            word.setWordId(Long.parseLong(ids[i]));
            Word word = wordDao.selectByPrimaryKey(Long.parseLong(ids[i]));
            word.setDelTag(Constants.YES); //是否删除 默认为0 1为删除
            result += wordDao.update(word);
//            result += wordDao.deleteByPrimaryKey(Long.parseLong(ids[i]));
        }
        if (result != ids.length) {
            BusinessException businessException = new BusinessException();
            businessException.setCode("删除信息失败！");
            throw businessException;
        }
        return result;
    }

    /**
     * 根据条件删除符合条件的Word对象
     *
     * @param word
     * @return 影响条件数
     */
    @Override
    public int delete(Word word) {
        return wordDao.delete(word);
    }

    /**
     * 插入Word对象
     *
     * @param word
     */
    @Override
    public void insert(Word word, String savePath) throws Throwable {
//        File file = fileDao.selectByPrimaryKey(word.getWordId());
//        file.setState(Constants.FILE_CLASS_STATE_ACTION);
//        fileDao.update(file);
        // 保存图片信息
        String imgFile = word.getImages();
        int index = imgFile.indexOf(",");
        imgFile = imgFile.substring(index + 1);

        Random random = new Random();
        String randomName = "" + random.nextInt(10000) + System.currentTimeMillis() + ".jpg";
        savePath = savePath + java.io.File.separator + randomName;
        Long tinyfileId = saveFileImage(randomName, ".jpg");
        base64StringToImage(imgFile, savePath);
        word.setFileId(tinyfileId);
        word.setDelTag(Constants.NOT);
        word.setCreateTime(new Date());
        int result = wordDao.insert(word);
        // 保存关系表
        UseFile useFile = new UseFile();
        useFile.setUseId(word.getWordId());
        useFile.setFileId(tinyfileId);
        useFile.setCreateTime(new Date());
        useFileDao.insert(useFile);
    }

    /**
     * 更新Word对象
     *
     * @param word
     * @return 影响条件数
     */
    @Override
    public void update(Word word, String savePath) {
        WordQuery wordQuery = wordDao.selectWordById(word.getWordId());
        if (word.getImages() != null && !"".equals(word.getImages())) {
            // 更新file信息
           /* File file = fileDao.selectByPrimaryKey(word.getFileId());
            file.setState(Constants.FILE_CLASS_STATE_ACTION);
            fileDao.update(file);*/
            // 保存图片信息[删除修改前的file]
            String imgFile = word.getImages();
            int index = imgFile.indexOf(",");
            imgFile = imgFile.substring(index + 1);
            Random random = new Random();
            String randomName = "" + random.nextInt(10000) + System.currentTimeMillis() + ".jpg";
            savePath = savePath + java.io.File.separator + randomName;
            Long tinyfileId = saveFileImage(randomName, ".jpg");
            base64StringToImage(imgFile, savePath);
            // 删除图片
            File oldImage = fileDao.selectByPrimaryKey(wordQuery.getFileId());
            oldImage.setDelTag(Constants.YES);
            oldImage.setUpdateTime(new Date());
            fileDao.update(oldImage);
            word.setFileId(tinyfileId);
            UseFile useFile = new UseFile();
            useFile.setUseId(word.getWordId());
            useFile.setFileId(tinyfileId);
            useFile.setCreateTime(new Date());
            useFileDao.insert(useFile);
            UseFile oldUseFile = useFileDao.select(new UseFile(wordQuery.getWordId(), wordQuery.getFileId())).get(0);
//            oldUseFile.setUseId(word.getWordId());
//            oldUseFile.setFileId(tinyfileId);
            oldUseFile.setDelTag(Constants.YES);
            useFileDao.update(oldUseFile);
        }
        word.setUpdateTime(new Date());
        wordDao.update(word);
        // 更新关系表
        // 删除图片
       /* UseFile oldUseFile = useFileDao.select(new UseFile(wordQuery.getWordId(), wordQuery.getFileId())).get(0);
//        com.breadenglish.cms.api.app.domain.db.File file2 = new com.breadenglish.cms.api.app.domain.db.File();
        file1 = fileDao.selectByPrimaryKey(oldUseFile.getFileId());
        file1.setDelTag(Constants.NOT);
        file1.setUpdateTime(new Date());
        fileDao.update(file1);
        oldUseFile.setDelTag(Constants.NOT);
        useFileDao.update(oldUseFile);*/
    }

    /**
     * 保存数据库
     *
     * @param fileName
     * @param extName
     * @return
     */
    private Long saveFileImage(String fileName, String extName) {
        com.breadenglish.cms.api.app.domain.db.File file = new com.breadenglish.cms.api.app.domain.db.File();
        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
        Long fileId = fileDao.getFileId();
        file.setFileId(fileId);
        file.setFileType(Constants.FILE_TYPE_TINY);
        file.setFileClass(Constants.FILE_CLASS_DEFAULT);
        file.setState(Constants.FILE_CLASS_STATE_ACTION);
        String src = PropertyConfigurerUtils.getProperty(Constants.FILE_SHOW_URL);
//        file.setFileUrl(src + File.separator + formater.format(new Date()) + File.separator + fileName);
        file.setFileUrl(src + formater.format(new Date()) + "/" + fileName);
        file.setFileName(fileName);
        file.setSize(0D);
        file.setExt(extName);
        file.setDelTag(Constants.NOT);
        file.setCreateTime(new Date());
        fileDao.insert(file);
        return fileId;
    }

    /**
     * 报错图片
     *
     * @param base64String
     * @param savePath
     */
    private static void base64StringToImage(String base64String, String savePath) {
        BASE64Decoder decoder = new sun.misc.BASE64Decoder();
        try {
            byte[] bytes1 = decoder.decodeBuffer(base64String);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            BufferedImage bi1 = ImageIO.read(bais);
            // 随机名字
//            Random random = new Random();
//            String randomName = "" + random.nextInt(10000) + System.currentTimeMillis() + ".jpg";
//            File w2 = new File(savePath + File.separator + randomName);
            java.io.File w2 = new java.io.File(savePath);
            ImageIO.write(bi1, "jpg", w2);
        } catch (IOException e) {
            logger.error("新增每日一词信息保存图片失败!");
        }
    }

    @Override
    public WordQuery queryWordById(Long wordId) {
        return wordDao.selectWordById(wordId);
    }

    @Override
    public List<WordQuery> queryWord(Word word) {
        return wordDao.queryWord(word);
    }
}
